<template>
  <div class="log-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>日志管理</span>
          <div>
            <el-button type="primary" @click="exportLogs">
              <el-icon><Download /></el-icon>
              导出日志
            </el-button>
            <el-button type="danger" @click="clearAllLogs">
              <el-icon><Delete /></el-icon>
              清空日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="日志级别">
            <el-select
              v-model="searchForm.level"
              placeholder="请选择日志级别"
              clearable
            >
              <el-option label="信息" value="info" />
              <el-option label="警告" value="warning" />
              <el-option label="错误" value="error" />
              <el-option label="调试" value="debug" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键词"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 日志表格 -->
      <el-table
        :data="logList"
        v-loading="loading"
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="timestamp" label="时间" width="180" />
        <el-table-column label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="message" label="消息" show-overflow-tooltip />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showLogDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteLog(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="800px"
    >
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ currentLog.timestamp }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLevelTagType(currentLog.level)">
              {{ getLevelText(currentLog.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="来源">{{ currentLog.source }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentLog.user || '系统' }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="log-message-detail">
          <h4>详细消息</h4>
          <pre>{{ currentLog.message }}</pre>
        </div>
        
        <div v-if="currentLog.stack_trace" class="log-stack-trace">
          <h4>堆栈跟踪</h4>
          <pre>{{ currentLog.stack_trace }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Delete } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentLog = ref(null)

const logList = ref([
  {
    id: 1,
    timestamp: '2024-01-15 14:30:25',
    level: 'info',
    source: 'system',
    message: '用户登录成功',
    user: 'admin',
    ip: '192.168.1.100'
  },
  {
    id: 2,
    timestamp: '2024-01-15 14:30:26',
    level: 'warning',
    source: 'auth',
    message: '密码错误次数过多',
    user: 'test',
    ip: '192.168.1.101'
  },
  {
    id: 3,
    timestamp: '2024-01-15 14:30:27',
    level: 'error',
    source: 'database',
    message: '数据库连接失败',
    stack_trace: 'Error: Connection timeout\n  at Database.connect (db.js:45)\n  at async main (app.js:12)'
  }
])

// 搜索表单
const searchForm = reactive({
  level: '',
  dateRange: [],
  keyword: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 3
})

// 获取日志级别标签类型
const getLevelTagType = (level: string) => {
  const typeMap: Record<string, string> = {
    info: 'success',
    warning: 'warning',
    error: 'danger',
    debug: 'info'
  }
  return typeMap[level] || 'info'
}

// 获取日志级别文本
const getLevelText = (level: string) => {
  const textMap: Record<string, string> = {
    info: '信息',
    warning: '警告',
    error: '错误',
    debug: '调试'
  }
  return textMap[level] || level.toUpperCase()
}

// 获取表格行类名
const getRowClassName = ({ row }: { row: any }) => {
  return `log-row-${row.level}`
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchLogList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    level: '',
    dateRange: [],
    keyword: ''
  })
  pagination.page = 1
  fetchLogList()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchLogList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchLogList()
}

// 获取日志列表
const fetchLogList = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 显示日志详情
const showLogDetail = (log: any) => {
  currentLog.value = log
  detailDialogVisible.value = true
}

// 删除日志
const deleteLog = async (log: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条日志吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = logList.value.findIndex(item => item.id === log.id)
    if (index > -1) {
      logList.value.splice(index, 1)
      pagination.total--
      ElMessage.success('日志删除成功')
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 导出日志
const exportLogs = () => {
  ElMessage.success('日志导出功能开发中')
}

// 清空所有日志
const clearAllLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有日志吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    logList.value = []
    pagination.total = 0
    ElMessage.success('所有日志已清空')
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLogList()
})
</script>

<style scoped>
.log-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  padding: 20px 0;
}

.log-message-detail,
.log-stack-trace {
  margin-top: 20px;
}

.log-message-detail h4,
.log-stack-trace h4 {
  margin-bottom: 10px;
  color: #333;
}

.log-message-detail pre,
.log-stack-trace pre {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

/* 表格行样式 */
:deep(.log-row-error) {
  background-color: #fef0f0;
}

:deep(.log-row-warning) {
  background-color: #fdf6ec;
}

:deep(.log-row-info) {
  background-color: #f0f9ff;
}

:deep(.log-row-debug) {
  background-color: #f5f7fa;
}
</style>
